//client.vala
//valac --pkg jsonrpc-glib-1.0 jsonclient.vala
using Jsonrpc;

public class RpcClient:GLib.Object{
	public Jsonrpc.Client c;
	public GLib.MainLoop loop1;

	public owned void rpcConnect(string host,uint16 port){
		Resolver resolver = Resolver.get_default ();
		List<InetAddress> addresses = resolver.lookup_by_name (host, null);
		InetAddress address = addresses.nth_data (0);
		SocketClient client = new SocketClient ();
		SocketConnection conn = client.connect(new InetSocketAddress (address, port));
		c = new Jsonrpc.Client(conn);
	}

	public void rpcClient(){
		string[] v = {"Hello friend.","无限恐怖","abcde"};
		var params = new Variant.strv(v);
		var loop = new GLib.MainLoop();
		int n=0;
		Variant res;
		
		GLib.AsyncReadyCallback f = (o,r)=>{
				Variant res1;
				c.call_async.end(r,out res1);
				stdout.printf("async : %s\n",res1.get_string());
			};
		var thread = new GLib.Thread<int>("subproc",()=>{
				for(int i=0;i<100;i++){
					try{
						c.call_async.begin("Arith.Hello",params,null,f);
					}catch (Error e) {
						stdout.printf ("Error: %s\n", e.message);
						loop.quit();
					}
				}
				return 0;
			});
		loop.run();
	}
	//idle.add everyone
	public void rpcClient1(){
		string[] v = {"Hello friend.","无限恐怖","abcde"};
		var params = new Variant.strv(v);
		var loop = new GLib.MainLoop();
		int n=0;
		Variant res;
		
		GLib.AsyncReadyCallback f = (o,r)=>{
				Variant res1;
				c.call_async.end(r,out res1);
				stdout.printf("async : %s\n",res1.get_string());
			};

			for(int i=0;i<20;i++){
				GLib.Idle.add(()=>{
					try{
						c.call_async.begin("Arith.Hello",params,null,f);
					}catch (Error e) {
						stdout.printf ("Error: %s\n", e.message);
						loop.quit();
					}
					return false;
				});
			}

		loop.run();
	}
	//idle.add everyone thread
	public void rpcClient2(){
		string[] v = {"Hello friend.","无限恐怖","abcde"};
		var params = new Variant.strv(v);
		var loop = new GLib.MainLoop();
		int n=0;
		Variant res;
		
		GLib.AsyncReadyCallback f = (o,r)=>{
				Variant res1;
				c.call_async.end(r,out res1);
				stdout.printf("async : %s\n",res1.get_string());
			};
			var thread = new GLib.Thread<int>("subproc",()=>{
				for(int i=0;i<20;i++){
					GLib.Idle.add(()=>{
						try{
							c.call_async.begin("Arith.Hello",params,null,f);
						}catch (Error e) {
							stdout.printf ("Error: %s\n", e.message);
							loop.quit();
						}
						return false;
					});
				}
				return 0;
			});
		loop.run();
	}

	public void init(){
		this.loop1 = new GLib.MainLoop();
	}
	public void run_loop(){
		this.loop1.run();
	}
	public void close(){
		c.close();
	}
}
void main(){
	var c = new RpcClient();
	c.rpcConnect("localhost",6666);
	//c.rpcClient();
	//c.init();
	c.rpcClient2();
	//c.run_loop();
	c.close();
	stdout.printf("end\n");
}
